﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
using System.Text;
using System.Threading;
using Common;

namespace PositionServer
{
    public class ThreadServiceHost
    {
        const int SleepTime = 100;
        private readonly ServiceHost _host = null;
        private Thread _thread;
        private bool _isRunning;
        public ThreadServiceHost()
        {
            NetTcpBinding netTcpBinding = new NetTcpBinding(SecurityMode.None, true)
                                              {
                                                  MaxBufferPoolSize = 2147483647,
                                                  //2g
                                                  MaxBufferSize = 2147483647,
                                                  MaxReceivedMessageSize = 2147483647,
                                                  SendTimeout = new TimeSpan(0, 10, 30),
                                                  ReceiveTimeout = new TimeSpan(20, 0, 10),
                                                  ReliableSession =
                                                      {
                                                          Enabled = true,
                                                          InactivityTimeout = new TimeSpan(20, 0, 10)
                                                      },
                                                  ReaderQuotas =
                                                      {
                                                          MaxArrayLength = 2147483647,
                                                          MaxStringContentLength = 2147483647,
                                                          MaxBytesPerRead = 2147483647
                                                      },
                                                  TransferMode = TransferMode.Buffered,
                                                  MaxConnections = 2147483647
                                              };

            _host = new ServiceHost(typeof(Service.PositionService));

            foreach (ChannelDispatcher channelDipsatcher in _host.ChannelDispatchers)
            {
                foreach (EndpointDispatcher endpointDispatcher in channelDipsatcher.Endpoints)
                {
                    endpointDispatcher.DispatchRuntime.AutomaticInputSessionShutdown = false;
                }
            }
            ServiceThrottlingBehavior throttlingBehavior =
                _host.Description.Behaviors.Find<ServiceThrottlingBehavior>();
            if (throttlingBehavior == null)
            {
                throttlingBehavior = new ServiceThrottlingBehavior { MaxConcurrentCalls = 2147483647, MaxConcurrentSessions = 2147483647 };
                _host.Description.Behaviors.Add(throttlingBehavior);
            }
            else
            {
                throttlingBehavior.MaxConcurrentCalls = 2147483647;
                throttlingBehavior.MaxConcurrentSessions = 2147483647;
            }

            //_host.Description.Endpoints
           // string strAddress = string.Format(@"net.tcp://{0}:" + ConstParameters.WcfPort + "/PositionServices", serverIp);
            string strAddress = string.Format(@"net.tcp://localhost:" + ConstParameters.WcfPort + "/PositionServices");
            ServiceEndpoint ep = _host.AddServiceEndpoint(typeof(Service.IPositionService), netTcpBinding, strAddress);

            foreach (OperationDescription op in ep.Contract.Operations)
            {
                DataContractSerializerOperationBehavior dataContractBehavior =
                    op.Behaviors.Find<DataContractSerializerOperationBehavior>();
                if (dataContractBehavior != null)
                {
                    dataContractBehavior.MaxItemsInObjectGraph = 2147483647;
                }
            }

            //_host.Open();
        }


        void RunService()
        {
            try
            {
                _isRunning = true;
                _host.Open();
                while (_isRunning)
                {
                    Thread.Sleep(SleepTime);
                }
                _host.Close();
                ((IDisposable)_host).Dispose();
            }
            catch (Exception)
            {
                if (_host != null)
                    _host.Close();
            }
        }
        public void Stop()
        {
            lock (this)
            {
                _isRunning = false;
            }
        }

        public void Start()
        {
            _thread = new Thread(RunService);
            _thread.Start();
        }

    }
}
